package com.cn.codebrush.二分查找;

/**
 * @Author Boolean
 * @Date 2022/5/9 21:35
 * @Version 1.0
 */
public class No33搜索旋转排序数组 {
    public static void main(String[] args) {
        int[] nums = {4,5,6,7,0,1,2};
        System.out.println(search(nums,0));
    }

    /**
     * 注意和 35 的区别
     * @param nums
     * @param target
     * @return
     */
    public static int search(int[] nums, int target) {
        int n = nums.length;
        int l = 0;
        int r = n-1;
        int mid =  (l+r)/2;
        while(l<=r){  //二分查找关键语句，查找时 用 l<=r ,查找并插入时 用 l<r
            if(nums[mid] == target){
                return mid;
            }else if(nums[mid] < nums[r]){
                if(nums[mid] < target && target <= nums[r]){
                    l = mid+1;
                }else {
                    r = mid;
                }
            }else {
                if(nums[mid] > target && target >= nums[l]){
                    r = mid;
                }else {
                    l = mid+1;
                }
            }
            mid =  (l+r)/2;
        }

        return -1;
    }

}
